﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HimVoiceStudio.Audio
{
    public class SampleReceivedEventArgs : EventArgs
    {
        public float[] Samples;
    }

    public class DisposableSampleNotifier : ISampleProvider, IDisposable
    {

        public event EventHandler<SampleReceivedEventArgs> OnSample;
        
        ISampleProvider _sampleProvider;
        public DisposableSampleNotifier(ISampleProvider baseProvider)
        {

            _sampleProvider = baseProvider;

        }
        int bufferPtr = 0;
        float[] theBuffer = new float[768];

        public WaveFormat WaveFormat => _sampleProvider.WaveFormat;

        public void Dispose()
        {
            if (_sampleProvider is IDisposable d)
            {
                d?.Dispose();
            }
        }

        public int Read(float[] buffer, int offset, int count)
        {
            int len = _sampleProvider.Read(buffer, offset, count);
            int chan = WaveFormat.Channels;
            for (int i = offset; i < offset + len; i += chan)
            {
                theBuffer[bufferPtr] = buffer[i];
                bufferPtr++;
                if (bufferPtr >= theBuffer.Length)
                {
                    bufferPtr = 0;
                    OnSample?.Invoke(this, new SampleReceivedEventArgs() { Samples = theBuffer });
                    break;
                }
            }
            return len;
        }



    }
}
